﻿using System;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using X.Web;
using X.Entity;
using System.IO;
using System.Drawing;

namespace X.WebSite.Admin.Product
{
    public partial class Detail : AdminPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                this.ddlCategoryId.DataSource = Bll.ProductCategory.GetCategoryList();
                this.ddlCategoryId.DataTextField = "CategoryName";
                this.ddlCategoryId.DataValueField = "CategoryId";
                this.ddlCategoryId.DataBind();

                if (!string.IsNullOrEmpty(Request.QueryString["ProductId"]))
                {
                    ProductInfo productInfo = Bll.Product.GetProduct(int.Parse(Request.QueryString["ProductId"]));

                    txtProductName.Text = X.Common.StringUtils.HtmlDecode(productInfo.ProductName);
                    ddlCategoryId.SelectedValue = productInfo.CategoryId.ToString();
                    txtPrice.Text = productInfo.Price.ToString();
                    chkIsHotProduct.Checked = productInfo.IsHotProduct;
                    chkIsAvailable.Checked = productInfo.IsAvailable;
                    chkIsRecommendatory.Checked = productInfo.IsRecommendatory;
                    txtTitle.Text = X.Common.StringUtils.HtmlDecode(productInfo.Title);
                    txtKeyword.Text = X.Common.StringUtils.HtmlDecode(productInfo.Keyword);
                    txtDescription.Text = X.Common.StringUtils.HtmlDecode(productInfo.Description);
                    txtTag.Text = productInfo.Tag;
                    ckeProductDescribe.Text = productInfo.ProductDescribe;

                    txtModel.Text = productInfo.Model;
                    txtPartNumber.Text = productInfo.PartNumber;
                    txtCertificate.Text = productInfo.Certificate;
                    txtColor.Text = productInfo.Color;
                    txtGuarantee.Text = productInfo.Guarantee;
                    txtHRC.Text = productInfo.HRC;
                    txtMaterial.Text = productInfo.Material;
                    txtOrderNum.Text = Convert.ToString(productInfo.OrderNum);

                    gvImages.DataSource = productInfo.Photo;
                    gvImages.DataBind();
                }
            }
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            ProductInfo productInfo;
            int productId = 0;

            if (!string.IsNullOrEmpty(Request.QueryString["ProductId"]))
            {
                productId = int.Parse(Request.QueryString["ProductId"]);

                productInfo = Bll.Product.GetProduct(productId);
            }
            else
            {
                productInfo = new ProductInfo();
            }

            productInfo.ProductName = X.Common.StringUtils.HtmlEncode(txtProductName.Text);
            productInfo.CategoryId = int.Parse(ddlCategoryId.SelectedValue);
            productInfo.SpecCategoryId = 0; //TODO:
            productInfo.Price = decimal.Parse(txtPrice.Text);
            productInfo.IsHotProduct = chkIsHotProduct.Checked;
            productInfo.IsAvailable = chkIsAvailable.Checked;
            productInfo.IsRecommendatory = chkIsRecommendatory.Checked;
            productInfo.Title = X.Common.StringUtils.HtmlEncode(txtTitle.Text);
            productInfo.Keyword = X.Common.StringUtils.HtmlEncode(txtKeyword.Text);
            productInfo.Description = X.Common.StringUtils.HtmlEncode(txtDescription.Text);
            productInfo.Tag = txtTag.Text;
            productInfo.ProductDescribe = ckeProductDescribe.Text;

            productInfo.Model = txtModel.Text;
            productInfo.PartNumber = txtPartNumber.Text;
            productInfo.Certificate = txtCertificate.Text;
            productInfo.Color = txtColor.Text;
            productInfo.Guarantee = txtGuarantee.Text;
            productInfo.HRC = txtHRC.Text;
            productInfo.Material = txtMaterial.Text;
            productInfo.OrderNum = Convert.ToInt32(txtOrderNum.Text);

            if (!string.IsNullOrEmpty(Request.QueryString["ProductId"]))
            {
                Bll.Product.Update(productInfo);
            }
            else
            {
                productId = Bll.Product.Create(productInfo);
            }

            UploadImage(productId);

            Response.Redirect("List.aspx");
        }

        const double WIDTH = 200;
        const double HEIGHT = 200;

        void UploadImage(int productId)
        {
            IList<string> list = new List<string>();

            HttpFileCollection files = Request.Files;

            for (int i = 0; i < files.Count; i++)
            {
                HttpPostedFile file = files[i];

                if (null != file && file.ContentLength > 0)
                {
                    string ext = Path.GetExtension(file.FileName);
                    string fileName = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                    string savePath = Server.MapPath("/Upload/");

                    file.SaveAs(savePath + fileName + ext); //原始

                    list.Add(fileName + ext);

                    System.Drawing.Image img = System.Drawing.Image.FromStream(file.InputStream, true);
                    double newWidth, newHeight;

                    if (img.Width > img.Height)
                    {
                        newWidth = WIDTH;
                        newHeight = img.Height * (newWidth / img.Width);
                    }
                    else
                    {
                        newHeight = HEIGHT;
                        newWidth = (newHeight / img.Height) * img.Width;
                    }

                    if (newWidth > WIDTH)
                        newWidth = WIDTH;
                    if (newHeight > HEIGHT)
                        newHeight = HEIGHT;

                    System.Drawing.Size size = new Size((int)newWidth, (int)newHeight);
                    System.Drawing.Image bitmap = new System.Drawing.Bitmap(size.Width, size.Height);
                    System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);
                    g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                    g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                    g.Clear(Color.White);

                    g.DrawImage(img, new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height), new System.Drawing.Rectangle(0, 0, img.Width, img.Height), System.Drawing.GraphicsUnit.Pixel);

                    //水印

                    bitmap.Save(savePath + fileName + "_s" + ext);
                    g.Dispose();
                    img.Dispose();
                    bitmap.Dispose();
                }
            }

            Bll.Product.UploadImage(productId, list);
        }

        protected void gvImages_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            int imageId = int.Parse(gvImages.DataKeys[e.RowIndex].Value.ToString());

            Bll.Product.DeleteImage(imageId);

            Response.Redirect("Detail.aspx?ProductId=" + Request.QueryString["ProductId"]);
        }
    }
}